<template>
	<view>
		<view class="shareback" @longtap="onLongtap">
			<view class="row sharestore">
				<image :src="storeInfo.store_pic"></image>
				<text>{{storeInfo.store_name}}</text>
			</view>
			<view class="row shareuser">
				<image :src="userInfo.avatar"></image>
				<text>{{userInfo.nickname}}</text>
			</view>
			<view class="sharemsg">我送了你一份【{{giveGoodsInfo.name}}】 喜欢就领取吧！</view>
			<view class="shareImagin">
				<image :src="giveGoodsInfo.image"></image>
			</view>
			<view class="share_rwm">
				<view>长按小程序码即可免费领取【{{giveGoodsInfo.name}}】一份</view>
				<image :src="qrcodeContent"></image>
			</view>
		</view>
		<view class="share_msg">* 长按保存图片转发朋友圈 *</view>
		<!-- <share-images id="share-images"></share-images> -->
		<!-- 使用组件画布不上 -->
		<view v-if="canvasHidden" style="margin-top:100rpx;">
			<canvas canvas-id="myCanvas" style="width:375px;height:542px;background:#fff;" />
		</view>
	</view>
</template>

<script>
	var app = getApp();
	import http from "@/common/js/request.js";
	export default {
		data() {
			return {
				canvasHidden: false,
				url: app.globalData.baseImgUrl,
				store_id: app.globalData.storeId,
				storeInfo: [],
				userInfo: [], //用户信息
				giveGoodsInfo: [],
			}
		},
		computed: {
			qrcodeContent: {

				get() {
					var timestamp = (new Date()).getTime();
					return app.globalData.qrcodeBaseUrl + escape(app.globalData.canvasShareBaseUrl + '&store_id=' + this.store_id +
						'&send_id=' + this.userInfo.id + '&goods_id=' + this.giveGoodsInfo.id + '&share_id=' + this.userInfo.id + "" +
						timestamp);

				}
			},

		},
		onShow() {
			var that = this;
			that.getStoreInfo();
			that.getUserInfo();
			that.giveGoodsInfo = app.globalData.giveGoodsInfo || [];
			uni.getSystemInfo({
				success(res) {
					that.screenWidth = res.screenWidth,
						that.screenHeight = res.screenHeight
				}
			})

		},
		methods: {
			//用户信息
			getUserInfo() {
				var that = this;
				http.post('/api/v1/member/member_info', {}, res => {
					that.userInfo = res.datas;
				});
			},
			//店铺详情
			getStoreInfo() {
				var that = this;
				http.post('/api/v1/store/store_detail', {
					store_id: that.store_id
				}, res => {
					that.storeInfo = res.datas;
				});
			},
			//长按保存图片
			onLongtap() {
				var that = this;
				// var timestamp = (new Date()).getTime();
				// console.log(app.globalData.qrcodeBaseUrl + escape(app.globalData.canvasShareBaseUrl + '&store_id=' + this.store_id +
				// '&send_id=' + this.userInfo.id + '&goods_id=' + this.giveGoodsInfo.id+'&share_id='+this.userInfo.id+""+timestamp))
				//console.log(that.screenWidth, that.screenHeight)
				that.canvasHidden = true;
				http.post("/api/v1/member/member_info", {}, function(res) {
					uni.downloadFile({
						url: res.datas.avatar,
						success(resavatar) {
							//下载头像
							console.log("头像", resavatar.tempFilePath);
							http.post("/api/v1/common/get_share_goods_img", {
								goods_id: app.globalData.giveGoodsInfo.id
							}, function(goodsres) {
								console.log("商品图片", goodsres.datas)
								if (goodsres.state == 1) {
									uni.downloadFile({
										url: goodsres.datas,
										success(goodresder) {
											console.log("商品图片", goodresder.tempFilePath)
											http.post("api/v1/common/get_share_store_img", {
												store_id: that.store_id
											}, function(storeres) {
												console.log(storeres, "店铺头像1111111111111111");
												uni.downloadFile({
													url: storeres.datas,
													success(storepicres) {
														console.log("店铺头像", storepicres.tempFilePath)

														uni.downloadFile({
															url: that.qrcodeContent,
															success(qrcoderes) {
																//下载二维码
																console.log("二维码", qrcoderes.tempFilePath);
																//	console.log(resavatar.tempFilePath, qrcoderes.tempFilePath, qrcoderes.tempFilePath, res.datas.nickname)
																//把当前画布指定区域的内容导出生成指定大小的图片
																var unit = that.screenWidth / 375;
																console.log('unit', unit)
																var butback = "https://store.qidian2018.com/uploads/images/share_bg.png";
																uni.downloadFile({
																	url: butback,
																	success: function(backres) {
																		console.log("背景图", backres.tempFilePath)
																		const ctx = uni.createCanvasContext('myCanvas', that)
																		ctx.drawImage(backres.tempFilePath, unit * 10, unit * 10, unit * 355, unit * 542);

																		//店铺名称
																		var store_name = that.storeInfo.store_name;
																		ctx.setFontSize(unit * 15);
																		ctx.setFillStyle('#fff');
																		ctx.fillText(store_name, unit * 100, unit * 66);
																		//店铺头像
																		var avatorWidth = unit * 66,
																			avatorHeight = unit * 66;
																		var avatarurlX = unit * 25; //绘制的头像在画布上的位置
																		var avatarurlY = unit * 25; //绘制的头像在画布上的位置
																		ctx.save();
																		ctx.beginPath()
																		ctx.arc(avatorWidth / 2 + avatarurlX, avatorHeight / 2 + avatarurlY, avatorWidth / 2,
																			0,
																			Math.PI *
																			2, false);
																		ctx.clip();
																		ctx.drawImage(storepicres.tempFilePath, unit * 25, unit * 25, avatorWidth,
																			avatorWidth);
																		ctx.restore();
																		//用户头像
																		var resWidth = unit * 66,
																			resHeight = unit * 66;
																		var reslX = unit * 105; //绘制的头像在画布上的位置
																		var reslY = unit * 105; //绘制的头像在画布上的位置
																		ctx.save();
																		ctx.beginPath(); //开始绘制
																		ctx.arc(resWidth / 2 + reslX, resHeight / 2 + reslY, resWidth / 2, 0, Math.PI *
																			2, false);
																		ctx.clip();
																		ctx.drawImage(resavatar.tempFilePath, unit * 105, unit * 105, resWidth, resHeight);
																		ctx.restore();
																		//用户名称
																		var nickname = res.datas.nickname;
																		ctx.setFontSize(unit * 15);
																		ctx.setFillStyle('#fff');
																		ctx.fillText(nickname, unit * 190, unit * 146);
																		//商品名称
																		var goodsName = "我送了你一份【" + that.giveGoodsInfo.name + "】喜欢就领取吧！ ";;
																		var chr = goodsName.split("");
																		var temp = "";
																		var row = [];
																		ctx.setFontSize(unit * 15)
																		ctx.setFillStyle("#fff")
																		ctx.setTextAlign("center")
																		for (var a = 0; a < chr.length; a++) {
																			if (ctx.measureText(temp).width < unit * 168) {
																				temp += chr[a];
																			} else {
																				a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
																				row.push(temp);
																				temp = "";
																			}
																		}
																		row.push(temp);
																		// console.log('row', row);

																		for (var b = 0; b < row.length; b++) {
																			ctx.fillText(row[b], unit * 189, unit * 220 + b * 24, 333);

																		}

																		//商品图片
																		console.log(goodresder.tempFilePath)
																		ctx.drawImage(goodresder.tempFilePath, unit * 126, unit * 273, unit * 136, unit *
																			133);

																		//分享商品文字展示
																		var textname = "长按小程序码即可免费领取【" + that.giveGoodsInfo.name + "】一份。"
																		var chr = textname.split("");
																		var temp = "";
																		var row = [];
																		ctx.setFontSize(unit * 14)
																		ctx.setFillStyle("#fff")
																		ctx.setTextAlign("left")
																		for (var a = 0; a < chr.length; a++) {
																			if (ctx.measureText(temp).width < unit * 138) {
																				temp += chr[a];
																			} else {
																				a--; //这里添加了a-- 是为了防止字符丢失，效果图中有对比
																				row.push(temp);
																				temp = "";
																			}
																		}
																		row.push(temp);
																		// console.log('row', row);

																		for (var b = 0; b < row.length; b++) {
																			ctx.fillText(row[b], unit * 29, unit * 466 + b * 28, unit * 396);

																		}
																		//二维码
																		ctx.drawImage(qrcoderes.tempFilePath, unit * 250, unit * 433, unit * 99, unit * 99);
																		ctx.draw();

																		//将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
																		setTimeout(function() {
																			uni.showLoading({
																				title: "保存中"
																			})
																			uni.canvasToTempFilePath({
																				canvasId: "myCanvas",
																				success: function(res) {
																					console.log(res,"chenggong")
																					var tempFilePath = res.tempFilePath;
																					if (!res.tempFilePath) {
																						uni.showModal({
																							title: "提示",
																							content: "图片绘制中，请稍后重试",
																							showCancel: false
																						})
																					}

																					uni.saveImageToPhotosAlbum({
																						filePath: res.tempFilePath,
																						//保存成功失败之后，都要隐藏画板，否则影响界面显示。
																						success: (res) => {
																							console.log(res, "")
																							that.canvasHidden = false;
																							uni.hideLoading();
																							wx.showToast({
																								title: '保存成功',
																							})

																						},
																						fail: (err) => {
																							console.log(err,"ddddd")
																							  if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
																							                               console.log("打开设置窗口");
																							                          that.imageErrorAuth()

																							                     }
																							uni.hideLoading()
																						}
																					})

																				},
																				fail: function(error) {
																					console.log("error")
																				}
																			})
																		}, 200)


																	}
																})

															},
															fail: function() {
																uni.showToast({
																	title: '二维码异常',
																	icon: 'none'
																})
															}
														})

													}
												})

											})
										}

									})

								} else {
									uni.showToast({
										title: '图片下载异常',
										icon: 'none'
									})
								}
							})

						},
						fail(res) {
							uni.showToast({
								title: '用户头像异常',
								icon: 'none'
							})
						}
					})
				})

			},

		
		
		
		
		imageErrorAuth() {
		      // 授权失败 提示授权操作
		      uni.showModal({
		        title: '提示',
		        content: '需要您授权保存至相册',
		        showCancel: false,
		        success: modalSuccess => {
		          uni.openSetting({
		            success(settingData) {
		              console.log("settingData", settingData)
		              if (settingData.authSetting['scope.writePhotosAlbum']) {
		                wx.showModal({
		                  title: '提示',
		                  content: '获取权限成功,再次保存图片即可',
		                  showCancel: false
		                })
		              } else {
		                uni.showModal({
		                  title: '提示',
		                  content: '获取权限失败，将无法保存到相册',
		                  showCancel: false
		                })
		              }
		            },
		            fail(failData) {
		              console.log("failData", failData)
		            },
		            complete(finishData) {
		              console.log("finishData", finishData)
		            }
		          })
		        }
		      })
		    },
		}
	}
</script>


<style>
	.shareback {
		background: url("http://petark-qiniu.qidian2018.com/c20453ef0a2b2c6fb7dc2556845ad945.png?v=854199") no-repeat;
		width: 709rpx;
		height: 1084rpx;
		margin: 0 auto;
		background-size: cover;
		overflow: hidden;
	}

	.sharestore {
		height: 132rpx;
		line-height: 132rpx;
		width: 669rpx;
		margin: 28rpx auto 0;
	}

	.sharestore image {
		width: 132rpx;
		height: 132rpx;
		border-radius: 50%;
	}

	.sharestore text {
		font-size: 30rpx;
		display: block;
		margin-left: 20rpx;
		color: #fff;
	}

	.shareuser {
		height: 115rpx;
		line-height: 115rpx;
		margin: 26rpx auto 0;
		width: 400rpx;

	}

	.shareuser text {
		margin-left: 20rpx;
		font-size: 30rpx;
		color: #fff;
	}

	.shareuser image {
		width: 115rpx;
		height: 115rpx;
		border-radius: 50%;
		vertical-align: middle;
	}

	.sharemsg {
		width: 408rpx;
		font-size: 30rpx;
		font-family: PingFang SC;
		font-weight: 400;
		color: rgba(255, 255, 255, 1);
		line-height: 60rpx;
		text-align: center;
		margin: 50rpx auto 0;
	}

	.shareImagin {
		width: 291rpx;
		height: 266rpx;
		border-radius: 10rpx;
		display: block;
		margin: 48rpx auto 0;
	}

	.shareImagin image {
		width: 100%;
		height: 100%;
	}

	.share_rwm {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		width: 669rpx;
		margin: 68rpx auto 0;
	}

	.share_rwm view {
		width: 334rpx;
		line-height: 66rpx;
		font-size: 28rpx;
		color: #fff;
		margin-top: 20rpx;
	}

	.share_rwm image {
		width: 198rpx;
		height: 198rpx;
	}

	.share_msg {
		height: 26rpx;
		font-size: 28rpx;
		font-family: PingFang SC;
		font-weight: 400;
		color: rgba(178, 178, 178, 1);
		line-height: 110rpx;
		text-align: center;
	}
</style>
